import { ref, onMounted, onUnmounted } from 'vue'
import { useAppStore } from '@/stores/app'

const WIDTH = 768 // 响应式断点

export function useDevice() {
  const appStore = useAppStore()
  const device = ref('desktop')

  const isMobile = () => {
    const rect = document.body.getBoundingClientRect()
    return rect.width - 1 < WIDTH
  }

  const resizeHandler = () => {
    if (!document.hidden) {
      const mobile = isMobile()
      device.value = mobile ? 'mobile' : 'desktop'

      // 如果有app store，更新设备类型
      if (appStore && appStore.toggleDevice) {
        appStore.toggleDevice(device.value)
      }
    }
  }

  onMounted(() => {
    // 初始化设备类型
    device.value = isMobile() ? 'mobile' : 'desktop'

    // 添加resize监听器
    window.addEventListener('resize', resizeHandler)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler)
  })

  return {
    device,
    isMobile
  }
}
